<template>
    <div>
        <a-form layout="inline">
            <a-form-model-item label="位置查询" prop="searchValue">
                <a-auto-complete  
                        placeholder="请输入内容"  
                            @search="handleSearch"  
                            @select="handleSelect"
                            allowClear>
                        <template slot="dataSource">
                            <a-select-option v-for="item in suggestions" :key="item.id" :title="item.title" :value="item.id">{{item.title}}</a-select-option>
                        </template>
                </a-auto-complete>  
            </a-form-model-item>
        </a-form>

        <div>位置：{{address||'请选择位置'}}</div>
        <div ref="searchMapRef" id="map_search_container" class="container"></div>
    </div>
</template>

<script>
import { debounce } from 'lodash'; // 或者你可以使用自己的防抖函数 
export default {
    name: "MapSearch",
    props:{
        location:{
            type: Object,
            default: ()=>{}
        },
    },
    data(){
        return{
            suggestions:[],
            address: "",
            mapLocation:{},
            center:{},
            map: null,
            isLoadScript:false,
        }
    },
    watch:{
        location:{
            handler(newVal){
                if(!this.map){
                    if(newVal && newVal.lat && newVal.lng){
                        //如果有地理位置
                        this.mapLocation = { lat:newVal.lat, lng:newVal.lng}; //显示标签的地理位置
                        this.center = { lat:newVal.lat, lng:newVal.lng}; //地图中心
                        this.address = newVal.address;
                        this.$nextTick(()=>{
                            this.initMap();
                        })
                    }else{
                        //如果没有地理位置
                        this.getMyLocation().then(res=>{
                            //获取当前位置作为地图中心点
                            this.center = res;
                            this.initMap();
                        })
                    }
                }
            },
            deep: true,
            immediate: true
        }
    },
    methods:{
        async getMyLocation() {
            const KEY = window._CONFIG['qqMapKey'];
            let url = 'https://apis.map.qq.com/ws/location/v1/ip';
            const resultRes = await this.$jsonp(url, { key: KEY, output: 'jsonp'});
            let location = {
                lat: resultRes.result.location.lat,
                lng: resultRes.result.location.lng
            }
            return location;
        },
        initMap() {
            //初始化地图
            var center = new TMap.LatLng(this.center.lat, this.center.lng);
            console.log("initMap:1", this.$refs["searchMapRef"]);
            this.map = new TMap.Map(this.$refs["searchMapRef"], {
                center: center,
                zoom: 14,   //设置地图缩放级别
                pitch: 0,  //设置俯仰角
                rotation: 0    //设置地图旋转角度
            });
            console.log("initMap:2");
            this.markerLayer = new TMap.MultiMarker({
                id: 'marker-layer',
                map: this.map,
            })

            this.map.on('click', (evt) => {
                console.log("evt", evt);
                this.mapLocation.lat = evt.latLng.lat
                this.mapLocation.lng = evt.latLng.lng
                const position = new TMap.LatLng(this.mapLocation.lat, this.mapLocation.lng);
                this.addOneMarker(position)
                const resultLocation = {
                    address: this.address,
                    lat:parseFloat(this.mapLocation.lat.toFixed(6)),
                    lng:parseFloat(this.mapLocation.lng.toFixed(6))
                };
                this.$emit("change", resultLocation);
            })

            if (this.mapLocation.lat && this.mapLocation.lng) {
                const position = new TMap.LatLng(this.mapLocation.lat, this.mapLocation.lng);
                this.addOneMarker(position)
            }
        },
        addOneMarker(position){
            this.markerLayer.remove("marker") //移除旧的标记
            this.markerLayer.add({
                id: "marker",
                position: position
            })
        },
        //地图搜索后的选项
        searchOptions(keyword){
            const KEY = "524BZ-SPPK6-QB3S6-MTGEU-OGZJ2-QCFYT";//这里是你自己的开发者秘钥
            let url = "https://apis.map.qq.com/ws/place/v1/suggestion";
            this.$jsonp(url, {
            key: KEY,
            keyword: keyword,
            output: "jsonp",
            }).then((res) => {
                this.suggestions = res.data;
            })
            .catch((err) => {
                console.log(err);
            });
        },
        handleSearch(value) {  
            //防抖搜索
            debounce(()=> {  
                this.searchOptions(value);
            }, 500)()
        },  
        handleSelect(value) {
            const suggestion = this.suggestions.find(item=> item.id ==value);
            this.address = suggestion.address
            this.mapLocation.lat = suggestion.location.lat;
            this.mapLocation.lng = suggestion.location.lng;
            const position = new TMap.LatLng(this.mapLocation.lat, this.mapLocation.lng);
            this.addOneMarker(position);
            this.map.panTo([this.mapLocation.lat, this.mapLocation.lng]);
            this.$emit("input", this.address);
            const resultLocation = {
                address: this.address,
                lat:parseFloat(this.mapLocation.lat.toFixed(6)),
                lng:parseFloat(this.mapLocation.lng.toFixed(6))
            };
            this.$emit("change", resultLocation);
        },
    }
}
</script>

<style>
.container{
    height: 500px;
    width:100%;
}
</style>